

//1.声明构造函数
function Promise(executor) {
  //4.添加属性
  this.PromiseState = 'pending'; //默认Promise实例对象状态属性
  this.PromiseResult = null; //默认Promise实例对象携带值
  const self = this; //保存Promise实例对象 resolve,reject函数内的this指向window
  this.callbacks = []; //8.执行器 executor 执行异步方法,并处理多个then方法调用
  //resolve 函数 功能实现
  function resolve(data) {
    if (self.PromiseState !== 'pending') return; //6.Promise 的状态只能修改一次
    self.PromiseState = 'fulfilled'; //4.修改Promise实例对象的状态属性
    self.PromiseResult = data; //4.对Promise的实例对象进行赋值
    self.callbacks.forEach(item=>{ //8.执行器 executor 执行异步方法,并处理多个then方法调用
      item.onResolved();
    })
  }
  //reject 函数  功能实现
  function reject(data) {
    if (self.PromiseState !== 'pending') return; //6.Promise 的状态只能修改一次
    self.PromiseState = 'rejected'; //4.修改Promise实例对象的状态属性
    self.PromiseResult = data; //4.对Promise的实例对象进行赋值
    self.callbacks.forEach(item=>{ //8.执行器 executor 执行异步方法,并处理多个then方法调用
      item.onRejected();
    })
  }
  //3.同步调用[执行器]函数
  try {
    executor(resolve, reject)
  } catch (error) {
    //5.处理 Promise 执行器内部抛出错误 改变 Promise 状态
    reject(error)
  }
}
//2.添加then方法
Promise.prototype.then = function (onResolved, onRejected) {
  if(typeof onRejected !== 'function'){ //10.异常穿透
    onRejected = (error)=>{throw error};
  }
  if(typeof onResolved !== 'function'){ //10.值传递
    onResolved = (value)=>{return value};
  }
  return new Promise((resolve,reject)=>{
    let self = this;
    function handleThen(onFunc){ //0 处理 then 返回 Promise实例对象 状态 同步异步状态下的封装
      let result = '';
      try {
        result = onFunc(self.PromiseResult)
        if(result instanceof Promise ){
          result.then((value)=>{
            resolve(value)
          },(error)=>{
            reject(error)
          })
        } else {
          resolve(result)
        }
      } catch (error) {
        reject(error);
      }
    }
    if (self.PromiseState === 'fulfilled') { //7.处理then方法的返回值
      handleThen(onResolved)
    }
    if (self.PromiseState === 'rejected') {  //7.处理then方法的返回值
      handleThen(onRejected)
    }
    if (self.PromiseState === 'pending') {  //8.执行器 executor 执行异步方法
        self.callbacks.push({
          onResolved:function(){handleThen(onResolved)},
          onRejected:function(){handleThen(onRejected)},
        })
    }
  })
};
//9.添加catch 方法
Promise.prototype.catch = function(onRejected){
  return this.then(undefined,onRejected);
}
